import {
  CanActivate,
  ExecutionContext,
  Inject,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
// import { Observable } from 'rxjs';
import { Request } from 'express';
import { RoleService } from '../role/role.service';
import { User } from '../user/entities/user.entity';
import { Permission } from './entities/permission.entity';
import { Reflector } from '@nestjs/core';

@Injectable()
export class PermissionGuard implements CanActivate {
  @Inject(RoleService)
  private roleService: RoleService;

  @Inject(Reflector)
  private reflector: Reflector;

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request: Request = context.switchToHttp().getRequest();
    const user = request.user as User;
    if (!user) {
      return true;
    }
    const userRoles = user.roles ?? [];
    const rolesList = await this.roleService.findRolesByIds(
      userRoles.map((v) => v.id),
    );
    // console.log('rolesList:==>', rolesList);

    const permissions: Permission[] = rolesList.reduce((res, item) => {
      res.push({ ...item.permissions });
      return res;
    }, []);

    // console.log('permissions:==>', permissions);

    const requiredPermissions =
      this.reflector.getAllAndOverride<string[]>('require-permission', [
        context.getClass(),
        context.getHandler(),
      ]) ?? [];

    // console.log('requiredPermissions:==>', requiredPermissions);
    for (const curPermission of requiredPermissions) {
      const found = permissions.find((item) => item.name === curPermission);
      if (!found) {
        throw new UnauthorizedException('您没有访问的权限');
      }
    }

    return true;
  }
}
